package com.rzjm.exercise.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class OssUtil {

    // endpoint以杭州为例，其它region请按实际情况填写。simple-mall.oss-cn-beijing.aliyuncs.com
    private static final String endpoint = "http://oss-cn-qingdao.aliyuncs.com";
    private static final String accessKeyId = "LTAI4G8N6NSmNotxiUAjYYwN";
    private static final String accessKeySecret = "imtY3O8AHOezHiLZb22ilJuAFm6umX";
    private static final String bucketName = "mini-car";

    public static final int TYPE_SHOP_PHOTOS = 1;//图片文件夹
    public static final int TYPE_TERMINAL_PHOTOS = 2;//图片文件夹
    public static final int TYPE_FACEURLS_PHOTOS = 3;//图片文件夹
    public static final int TYPE_TEMPRO_PHOTOS = 4;//图片文件夹
    public static final int TYPE_POST_PHOTOS = 5;//图片文件夹
    public static final int TYPE_ROOM_PHOTOS = 6;//图片文件夹
    public static final int TYPE_ARTICLE_PHOTOS = 7;//图片文件夹

    public static final int TYPE_DEVICE_RANGE_PHOTOS = 8;//图片文件夹
    public static final int TYPE_DEVICE_PHOTOS = 9;//图片文件夹
    public static final int TYPE_DEVICE_WELDING_PHOTOS = 10;//图片文件夹

    private static final String SHOP_IMG_PREFIX  = "shop/";
    private static final String TERMINAL_IMG_PREFIX  = "terminal/";
    private static final String FACEURLS_IMG_PREFIX  = "faceimg/";
    private static final String TEMPRO_IMG_PREFIX  = "tempro/";
    private static final String POST_IMG_PREFIX  = "post/";
    private static final String ROOM_IMG_PREFIX  = "room/";
    private static final String ROOM_ARTICLE_PREFIX  = "article/";
    private static final String DEVICE_RANGE_PREFIX  = "range/";
    private static final String DEVICE_PREFIX  = "device/";
    private static final String DEVICE_WELDING_PREFIX  = "welding/";


    /**
     * 获取  上传图片的 路径前缀
     * @param upload_type
     * @return
     */
    public static String getUploadPrefix(int upload_type){
        String prefix = null;
        switch (upload_type) {
            case TYPE_SHOP_PHOTOS:
                prefix = SHOP_IMG_PREFIX;
                break;
            case TYPE_TERMINAL_PHOTOS:
                prefix = TERMINAL_IMG_PREFIX;
                break;
            case TYPE_FACEURLS_PHOTOS:
                prefix = FACEURLS_IMG_PREFIX;
                break;
            case TYPE_TEMPRO_PHOTOS:
                prefix = TEMPRO_IMG_PREFIX;
                break;
            case TYPE_POST_PHOTOS:
                prefix = POST_IMG_PREFIX;
                break;
            case TYPE_ROOM_PHOTOS:
                prefix = ROOM_IMG_PREFIX;
                break;
            case TYPE_ARTICLE_PHOTOS:
                prefix = ROOM_ARTICLE_PREFIX;
                break;
            case TYPE_DEVICE_RANGE_PHOTOS:
                prefix = DEVICE_RANGE_PREFIX;
                break;
            case TYPE_DEVICE_PHOTOS:
                prefix = DEVICE_PREFIX;
                break;
            case TYPE_DEVICE_WELDING_PHOTOS:
                prefix = DEVICE_WELDING_PREFIX;
                break;
        }
        return prefix;
    }


    private static final int validity = 60 * 1000;

    public static void main(String args[]){
       /* String url = "/article/1/2c1157af-7612-43bd-b34c-e928338ab6a9.png";
        url = url.substring(1,url.length());
        boolean bl = deleteObjByKey(url);
        if(bl){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }*/
        System.out.println(getSignUrl("article/1.png"));
    }

    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     * @param upload_type 要上传的文件类型
     */
    public static boolean upload(InputStream inputStream,String fileName,int upload_type) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
            String prefix = getUploadPrefix(upload_type);
            if (prefix!=null){
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, prefix + fileName, inputStream);
                String eTag = putObjectResult.getETag();
                System.out.println("upload "+fileName +"-->"+ eTag);
            }
            // 关闭client。
            ossClient.shutdown();
        }
        System.out.println("upload "+fileName +"是否成功-->"+ (ret?"YES":"NO"));
        return ret;
    }

    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     */
    public static boolean upload(InputStream inputStream,String fileName) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
//            String prefix = getUploadPrefix(upload_type);
            if (fileName!=null){
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream);
                String eTag = putObjectResult.getETag();
                System.out.println("upload "+fileName +"-->"+ eTag);
            }
            // 关闭client。
            ossClient.shutdown();
        }
        System.out.println("upload "+fileName +"是否成功-->"+ (ret?"YES":"NO"));
        return ret;
    }

    /**
     * 根据key获取url
     * @param object_key
     * @return
     */
    public static String getSignUrl(String object_key){
        //创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        //validity url的有效期
        URL url = ossClient.generatePresignedUrl(bucketName, object_key, new Date(new Date().getTime()+validity));;
        //关闭client
        ossClient.shutdown();
        return url==null?null:url.toString();
    }


    /**
     * 删除文件
     * @param objKey
     * @return
     */
    public static boolean deleteObjByKey(String objKey) {
        boolean ret = false;
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        ossClient.deleteObject(bucketName,objKey);
        // Object是否存在。
        ret = ossClient.doesObjectExist(bucketName, objKey);
        ossClient.shutdown();
        return !ret;
    }


    public static BufferedImage getImageInfoByUrl(String urlStr){

        try{
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            int length = urlConnection.getContentLength();
            System.out.print("length: " + length);
            if(length == -1){
                System.out.print("image not exist");
            }else{
                BufferedImage sourceImg = ImageIO.read(url);
                System.out.print("image width:" + sourceImg.getWidth());
                System.out.print("image height:" + sourceImg.getHeight());
                return sourceImg;
            }
        }catch (MalformedURLException e){
//            logger.info("url not right " + e.getMessage(), e);
        } catch (IOException e){
//            logger.info("IOException " + e.getMessage(), e);
        }
        return null;
    }

    public void download(String fileName, String filePath, HttpServletResponse response){

          /* InputStream in = new FileInputStream(new File(batchDO.getFileUrl()));//将该文件加入到输入流之中
        byte[] body = null;
        body = new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取（或跳过）的估计剩余字节数
        in.read(body);//读入到输入流里面*/

//        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-msdownload");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject  = ossClient.getObject(bucketName, filePath);

            BufferedInputStream input = new BufferedInputStream(ossObject.getObjectContent());
            byte[] buffBytes = new byte[1024];
            OutputStream outputStream  = response.getOutputStream();
            int read = 0;
            while ((read = input.read(buffBytes)) != -1) {
                outputStream.write(buffBytes, 0, read);
            }
            outputStream.flush();

            // ossObject对象使用完毕后必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            ossObject.close();

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

}
